package com.edu.user.intcep;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.edu.user.domain.po.User;
import com.edu.user.utils.JwtUtil;
import com.edu.user.utils.ThreadLocalUtil;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.edu.user.utils.RedisConstants.LOGIN_USER_KEY;
import static com.edu.user.utils.RedisConstants.LOGIN_USER_TTL;


/*
* 刷新token的拦截器
* */

public class RefreshTokenInterceptor implements HandlerInterceptor {
    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response, Object handler) throws Exception {

        // 1请求头中的token
        String authorization = request.getHeader("authorization");
        System.out.println("token:"+authorization);
        if(StrUtil.isBlank(authorization)){

            return true;
        }
        //2基于TOKEN 获取Redis中的用户
        String key=LOGIN_USER_KEY+authorization;
        String token = stringRedisTemplate.opsForValue().get(key);

        Map<String, Object> userMap = JwtUtil.parseToken(authorization);

        //3判断用户是否存在
        if(userMap.isEmpty()){

            return true;
        }

        // 5将查询到的Hash数据转为UserDTO对象
        User userDTO = BeanUtil.fillBeanWithMap(userMap, new User(), false);

        // 6存在，保存用户信息到ThreadLocal
        ThreadLocalUtil.set(userDTO);
        // 7刷新token有效期
        stringRedisTemplate.expire(key,LOGIN_USER_TTL, TimeUnit.MINUTES);
        //8放行
        return true;
    }

    @Override
    public void afterCompletion(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除用户
        ThreadLocalUtil.remove();
    }




}
